package com.winshare.saleAssistant.controller;

import com.aliyun.oss.OSSException;
import com.winshare.saleAssistant.domain.dto.req.FileDTO;
import com.winshare.saleAssistant.domain.dto.req.FileDeleteDTO;
import com.winshare.saleAssistant.exception.BusinessException;
import com.winshare.saleAssistant.service.FileService;
import com.winshare.saleAssistant.util.LogicResponse;
import com.winshare.saleAssistant.util.SecurityManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

@Api(value = "图片上传", description = "图片上传")
@RestController(value = "/sys/file")
@CrossOrigin
public class FileController {

    private final FileService fileService;

    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    @PostMapping("/upload")
    @ApiOperation(value = "上传文件",notes = "上传文件")
    public LogicResponse<String> upload(@RequestParam (value = "mFile")MultipartFile file) {
        FileDTO fileDTO = new FileDTO();
        try {
            fileDTO.setFileContent(SecurityManager.entryptBase64(file.getBytes()));
            String randomFileName = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
            String fileName = file.getOriginalFilename();
            String fileNamePostFix = fileName.split("\\.")[1];
            fileDTO.setFileName(randomFileName+"."+fileNamePostFix);
            String upload = fileService.upload(fileDTO);
            return LogicResponse.success(Optional.ofNullable(upload).orElse(null));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OSSException e) {
            throw new BusinessException(e.getMessage());
        }
        return null;
    }

    @PostMapping("/delete")
    @ApiOperation(value = "根据链接url删除文件",notes = "根据链接url删除文件")
    public LogicResponse delete(@RequestBody @Validated FileDeleteDTO fileDeleteDTO) {
        fileService.delete(fileDeleteDTO);
        return LogicResponse.success("success");
    }
}
